package org.test.rocketmq.consumer;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;
import org.test.rocketmq.RocketmqConfig;

@Component
public class RocketmqConsumer implements SmartLifecycle {
    private static final Logger LOGGER = LoggerFactory.getLogger(RocketmqConsumer.class);

    private final RocketmqConfig rocketmqConfig;

    private boolean running;

    public RocketmqConsumer(RocketmqConfig rocketmqConfig) {
        this.rocketmqConfig = rocketmqConfig;
    }

    @Override
    public void start() {
        //消费者的组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(rocketmqConfig.getConsumer().getGroup());

        //指定NameServer地址，多个地址以 ; 隔开
        consumer.setNamesrvAddr(rocketmqConfig.getNamesrvAddr());
        try {
            //订阅PushTopic下Tag为push的消息
            consumer.subscribe("TopicTest", "push");

            //设置Consumer第一次启动是从队列头部开始消费还是队列尾部开始消费
            //如果非第一次启动，那么按照上次消费的位置继续消费
            consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
            consumer.registerMessageListener((MessageListenerConcurrently) (list, context) -> {
                try {
                    for (MessageExt messageExt : list) {
                        //输出消息内容
                        LOGGER.info("messageExt{}", messageExt);

                        String messageBody = new String(messageExt.getBody(), RemotingHelper.DEFAULT_CHARSET);
                        //输出消息内容
                        LOGGER.info("消费响应：msgId : {},   msgBody : {}", messageExt.getMsgId(), messageBody);
                    }
                } catch (Exception e) {
                    LOGGER.warn("deal message exception", e);
                    //稍后再试
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                //消费成功
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            });
            consumer.start();
            this.running = true;
        } catch (Exception e) {
            LOGGER.error("consumer message exception", e);
        }
    }

    @Override
    public void stop() {
        // do nothing
    }

    @Override
    public boolean isRunning() {
        return running;
    }
}
